package utils;

import java.sql.*;

public class JDBCutil{
private static PreparedStatement ps;
private static Connection con;
private static ResultSet rs;
public static Connection getCon(){
    return con;
}
static{
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","123");
    } catch (Exception e) {
     throw new RuntimeException(e+"连接数据库失败");
    }
}
public static int excuteupdate(String sql,Object obj[]){
    int result=-1;
    try {
        ps = con.prepareStatement(sql);
        for(int i=0;i<obj.length;i++){
            ps.setObject(i+1,obj[i]);
        }
        result=ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
return result;

}
//查询全部数据
public static ResultSet excuteQuery(String sql){
    try {
        ps=con.prepareStatement(sql);
        rs=ps.executeQuery();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return rs;
}
//查询单条数据
public static ResultSet excuteQuery(String sql,Object []obj){
    try {
        ps=con.prepareStatement(sql);
        for(int i=0;i<obj.length;i++) {
            ps.setObject(i+1,obj[i]);
        }
        rs=ps.executeQuery();
    } catch (SQLException e) {
        e.printStackTrace();
    }
return rs;
}
public static void close(){
    try {
        if(con!=null){
            con.close();
    }
        if(ps!=null){
            ps.close();
        }
        if(rs!=null){
            rs.close();
        }
    } catch (SQLException e) {
            e.printStackTrace();
        }



}

}